#!/usr/bin/bash
[[ $# -ne 1 ]] && echo -e "[error] 需要输入客户端IP作为参数\nUsage: bash $0 client_IP\nSample: bash $0 houseschan.gicp.net" && exit 1
pro_base="$(cd `dirname $(readlink -f $0)`;pwd)"        # program base directory. readlink是为了获取脚本的真实路径
#pro_root="${pro_base##*/}"                              # 我的程序的根目录名字.   readlink使得ln创建的软链也能正确地执行
#pro_name="$(readlink -f $0 | sed 's#^.*/##; s#.sh$##')" # 删除'/'前的路径,删除'.sh'

source ${pro_base}/shared/include.sh || exit 1
Include ${pro_base}/shared/prompt.sh

Eval_exit "dnf install -y squid httpd-tools openssl"    # httpd-tools 安装包中含 htpasswd 命令

# 插入新行之前,先删除,避免重复插入
sed -i '/auth_param basic/d
/acl CE/d
/acl Safe_IPs/d
/http_access allow Safe_IPs/d
/https_port 3390/d' /etc/squid/squid.conf               # <newline>是sed的命令分隔符,应养成良好的sed编程习惯,一行一个命令

# 插入新行
sed -i '1i \
auth_param basic program /usr/lib64/squid/basic_ncsa_auth /etc/squid/squid_user.txt\
auth_param basic children 5\
auth_param basic realm Welcome to HousesChan\"s proxy-only web server\
acl CE proxy_auth REQUIRED
# 备注:上面的REQUIRED后面没有反斜杠"\",说明前面的i命令到此结束.以"#"开头的是注释行,命令与命令之间可以存在空行

/acl SSL_ports port 443/i acl Safe_IPs src houseschan.gicp.net\
acl Safe_IPs src 27.39.66.0/24 27.39.71.0/24 120.87.143.0/24  # 222之6号四楼联通IP
# 如果你的IP不在这些Safe_IPs范围,访问互联网时会出现下面的错误信息:
# Access control configuration prevents your request from being allowed at this time. Please contact your service provider if you feel this is incorrect.

# 禁止监听不加密的普通端口
s/.*http_port 3128.*/#&/
# 监听加密的SSL端口
/^http_access allow localhost$/a \
http_access allow Safe_IPs CE\
https_port 3390 cert=/etc/squid/houses.crt key=/etc/squid/houses.key' /etc/squid/squid.conf

sed -i '/coredump_dir / a\
access_log /var/log/squid/access.log combined\
logformat combined %<a %ui %un [%tl] "%rm %ru HTTP/%rv" %Hs %<st "%{Referer}>h" "%{User-Agent}>h" %Ss:%Sh\
cache_dir ufs /var/spool/squid 1000 16 256\
minimum_object_size 0 KB\
maximum_object_size 4096 KB\
cache_swap_low 90\
cache_swap_high 95\
logfile_rotate 60\
cache_log /var/log/squid/cache.log' /etc/squid/squid.conf

echo 'forwarded_for delete' >> /etc/squid/squid.conf
#echo 'forwarded_for transparent' >> /etc/squid/squid.conf   # 透明代理？
#echo 'request_header_access Via deny all
#request_header_access X-Forwarded-For deny all' >> /etc/squid/squid.conf # 高匿代理，删除x-forward-for头


cd /etc/squid/
openssl req -x509 -days 3650 -new -nodes -keyout houses.key -out houses.crt

{
htpasswd -nb chq99 99chq
htpasswd -nb chq98 98chq
htpasswd -nb chq97 97chq
htpasswd -nb chq96 96chq
htpasswd -nb chq95 95chq
htpasswd -nb chq94 94chq
htpasswd -nb chq93 93chq
htpasswd -nb chq92 92chq
htpasswd -nb chq91 91chq
htpasswd -nb chq90 90chq
} >> /etc/squid/squid_user.txt

sed -i '/# 这中间可以执行任何其他代码或脚本/a systemctl status squid' /etc/rc.d/rc.local

systemctl enable squid
systemctl restart squid
systemctl status squid
